package com.example.demo.service.impl;

import com.example.demo.entity.*;
import com.example.demo.mapper.OptionMapper;
import com.example.demo.mapper.TopicMapper;
import com.example.demo.service.Topicservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class Topicservicelipm implements Topicservice {

    @Autowired
    TopicMapper topicMapper;
    @Autowired
    OptionMapper optionMapper;

    @Override
    public List<Topic> list(String name) {
        name = name ==null?"":name;
        TopicExample topicExample = new TopicExample();
        topicExample.createCriteria().andTnameLike("%"+name+"%");
        List<Topic> list = topicMapper.selectByExample(topicExample);
        return list;
    }

    @Override
    public void add(TopicOption topicOption) {
        Topic topic = topicOption.getTopic();
        topicMapper.insertSelective(topic);
        for(Option option :topicOption.getOptions()){
            option.setTid(topic.getTid());
            optionMapper.insert(option);
        }
    }
    @Override
    public void update(TopicOption topicOption) {
        topicMapper.updateByPrimaryKeySelective(topicOption.getTopic());
        OptionExample optionExample = new OptionExample();
        optionExample.createCriteria().andTidEqualTo(topicOption.getTopic().getTid());
        optionMapper.deleteByExample(optionExample);
        for(Option option :topicOption.getOptions()){
            optionMapper.insert(option);
        }
    }

    @Override
    public void del(Integer[] ids) {
        for(Integer i:ids){
            OptionExample optionExample = new OptionExample();
            optionExample.createCriteria().andTidEqualTo(i);
            optionMapper.deleteByExample(optionExample);
            topicMapper.deleteByPrimaryKey(i);
        }
    }

    @Override
    public TopicOption getTopicOption(Integer tid) {
        //获取题目
        Topic topic = topicMapper.selectByPrimaryKey(tid);
        //获取选项
        OptionExample optionExample = new OptionExample();
        optionExample.createCriteria().andTidEqualTo(tid);
        List<Option> options = optionMapper.selectByExample(optionExample);
        return new TopicOption(topic,options);
    }

    @Override
    public TopicOption listoption(Integer tid) {

        Topic topic = topicMapper.selectByPrimaryKey(tid);


            OptionExample optionExample = new OptionExample();
            optionExample.createCriteria().andTidEqualTo(tid);
            List<Option> options = optionMapper.selectByExample(optionExample);
            TopicOption topicOption = new TopicOption(topic,options);

        return topicOption;
    }


}
